<?php
/**
 * LowCalVanilla Functions
 *
 * @package Extensions
 * @subpackage Low-Cal_Vanilla
 * @copyright Damien Lebrun 2007
 * @author Damien Lebrun
 * @license http://www.gnu.org/licenses/old-licenses/gpl-2.0.html GPLv2
 * @version @@VERSION@@
 */


/**
 * Check the client can receive gz encoded content
 * @return bool
 */
function LowCalVanilla_AcceptGzip($Configuration) {
	if ( $Configuration['LOWCALVANILLA_GZIP_ALLOWED']
	  && !IsGzipIncompatibleClient()
	  && !empty($_SERVER['HTTP_ACCEPT_ENCODING'])
	  && preg_match('/gzip/', $_SERVER['HTTP_ACCEPT_ENCODING'])
	) {
		return true;
	} else {
		return false;
	}
}

/**
 * Remove the 4 core js file in Head::Scripts
 * @return void
 */
function LowCalVanilla_PackJsFiles(&$Head) {
	if ($Head->Context->Configuration['SELF_URL'] != 'people.php') {
		// Replace the first of the 4 script with the packed one
		$ScriptRoot = $Head->Context->Configuration['WEB_ROOT'];
		$GlogalPath = ConcatenatePath($ScriptRoot, 'js/global.js');
		$key = array_search($GlogalPath, $Head->Scripts);
		if ($key !== false) {
			$Packed = ConcatenatePath(
				$ScriptRoot,
				'extensions/LowCalVanilla/compressor.php?uri=extensions/LowCalVanilla/js/vanilla-packed.js');
			$Head->Scripts[$key] = $Packed;

			// Unset the other ones
			$OtherPath = array('js/vanilla.js', 'js/ajax.js', 'js/ac.js');
			foreach ($OtherPath as $Path) {
				$ScriptPath = ConcatenatePath($ScriptRoot, $Path);
				$key = array_search($ScriptPath, $Head->Scripts);
				if ($key !== false) {
					unset($Head->Scripts[$key]);
				}
			}
			$Head->Scripts = array_values($Head->Scripts);
		}
	}
}


/**
 * Set the RequestedFile class
 * @return array $Configuration
 * @return RequestedFile
 */
function GetFileToServe($Context) {
	$MineTypes = array(
		'js' => 'text/javascript',
		'css' => 'text/css'
	);

	$ThemePattern = '/^themes\/([-_\.~a-zA-Z0-9]+)\/styles\/([-_\.~a-zA-Z0-9]+)\/([-_\.~a-zA-Z0-9]+).css$/';
	$GeneralPattern = '/^.*\/([-_\.~a-zA-Z0-9]+)\.(js|css)$/';
	$Uri = ForceIncomingString('uri', '');

	if (@preg_match($ThemePattern, $Uri, $Details)) {
		$LowCalPath = LOWCALVANILLA_DIR . '/css/themes/' . $Details[1] . '/' . $Details[2] . '/' . $Details[3] . '.css';
		$Mime = $MineTypes['css'];
	} elseif (@preg_match($GeneralPattern, $Uri, $Details)){
		$LowCalPath = LOWCALVANILLA_DIR . '/' . $Details[2] . '/' . $Details[1] . '.' . $Details[2];
		$Mime = $MineTypes[$Details['2']];
	} else {
		return false;
	}

	//check the resqueted file can be serve.
	$Servable = 0;
	if ($RealPath = realpath($Context->Configuration['APPLICATION_PATH'] . $Details[0])) {
		$RealPath = str_replace('\\', '/', $RealPath);
		$Pattern = preg_quote($Context->Configuration['APPLICATION_PATH'], '/');
		$Pattern = '/^'.$Pattern.'(js|themes|extensions).*$/';
		$Servable = preg_match(
			$Pattern,
			$RealPath);
	}

	if ($Servable) {
		$Try = array();
		// Should we server compressed files to get the gunzip one
		if ( LowCalVanilla_AcceptGzip($Context->Configuration) ) {
			$Try[] = array($LowCalPath . '.gz', 'gzip');
			$Try[] = array($RealPath . '.gz', 'gzip');
		}
		$Try[] = array($LowCalPath, '');
		$Try[] = array($RealPath, '');
	} else {
		return false;
	}

	$Encoding = '';
	for ($i=0 ; $i < count($Try); $i++) {
		if (file_exists($Try[$i][0])) {
			$Path = str_replace('\\', '/', $Try[$i][0]);
			$Encoding = $Try[$i][1];
			break;
		}
	}

	if ($Path) {
		return new LowCalVanilla_FileToServe($Context, $Path, $Mime, $Encoding);
	} else {
		return false;
	}
}

/**
 * Sniff for browser having issue with gzip content.
 * @param bool $ResponseForNoInfo What to return if USER_AGENT is not set
 * @return bool Return true if you cannot believe Accept-Encoding
 * @uses $_SERVER['HTTP_USER_AGENT']
 * @link http://support.microsoft.com/kb/321722/EN-US/
 * @link http://support.microsoft.com/default.aspx?scid=kb;[LN];Q312496
 */
function IsGzipIncompatibleClient($ResponseForNoInfo = true) {

	// return if $_SERVER['HTTP_USER_AGENT'] is not set
	if (empty($_SERVER['HTTP_USER_AGENT'])) {
		return $ResponseForNoInfo;
	}

	/**
	 * Netscape 4.0 and IE6 have some bugs with gzip content evevn if they are supposed to accept it.
	 * Also, gunzip content will always be cached in IE5.5 and IE6
	 */
	$Pattern = '/(Mozilla\/4\.0(?!.*\b(MSIE|opera|safari))|\bMSIE (5\.5|6\.0))/i';
	if (preg_match($Pattern, $_SERVER['HTTP_USER_AGENT'])) {
		return true;
	}
	return false;
}

/**
 * Add Low-Cal vanilla settings to conf/settings.php (no settings yet).
 * @param Context $Context Vanilla context object
 * @return void
 */
function InstallLowCalVanilla(&$Context) {
	if (!array_key_exists('LOWCALVANILLA_VERSION', $Context->Configuration)) {
		AddConfigurationSetting($Context, 'LOWCALVANILLA_GZIP_ALLOWED', '1');
		AddConfigurationSetting($Context, 'LOWCALVANILLA_EXPIRE', '86400');
		AddConfigurationSetting($Context, 'LOWCALVANILLA_VERSION', '0.3.0');
	}
}